﻿define([
  'models/abmManagers/rolManager',
  'models/security/session',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/rol/common/rolCreate.html',
], function (RolModel, sessionModel, BaseTmp, FormTmp, UniqTmp) {

    var view = Backbone.View.extend({

        el: $("#main"),
        _uId: "",
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-rol']").remove();
            var _this = this;
            this._uId = $.uuid();
            var sessModel = new sessionModel();
            sessModel.getAllProcess(function (dataSession) {
                var baseTemplate = Handlebars.compile(BaseTmp);
                var formTemplate = Handlebars.compile(FormTmp);
                var uniqTemplate = Handlebars.compile(UniqTmp);

                var dataBaseTemplate = {
                    id: _this._uId,
                    dataRel: "abm-rol", // cuidado, ref en js
                    tmpClass: "rol-create", // cuidado, ref en css
                    title: translate("_newRol")
                };
                var dataUniqTemplate = {
                    procGroup: _this.prepareProcess(dataSession)
                };

                var html = baseTemplate(dataBaseTemplate);
                var html2 = formTemplate();
                var html3 = uniqTemplate(dataUniqTemplate);

                _this.$el.append(html);
                $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);
                
                postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                _this.addHandlers();
                _this.loadMultiSelect();
                $("#mainLoading").hide();
            });
        },
        prepareProcess: function (data) {
            var oldGroup = data[0].group.groupName;
            var j = 0;
            var k = 1;
            var finalData = [];

            finalData[j] = {
                group: oldGroup,
                process: [{
                    name: data[0].processName,
                    code: data[0].code
                }]
            };
            
            for (var i = 1; i < data.length ; i++) {
                if (oldGroup == data[i].group.groupName) {
                    finalData[j].process.push({
                        name: data[i].processName, code: data[i].code
                    });
                    k++;
                }
                else {
                    k = 0;
                    j++;
                    oldGroup = data[i].group.groupName;
                    finalData[j] = { group: oldGroup, process: [] };
                    finalData[j].process.push({
                        name: data[i].processName, code: data[i].code
                    });
                }
            }
            return finalData;
        },
        loadMultiSelect: function () {
            var _this = this;
            var eSelect = $("div[data-id='" + _this._uId + "']").find("div.process-selection select");
            var selectableHeader = eSelect.attr('data-selectableheader'),
			selectionHeader = eSelect.attr('data-selectionheader');
            eSelect.multiSelect({
                selectionHeader: "<div class='multi-custom-header'>" + selectionHeader + "</div>",
                selectableHeader: "<div class='multi-custom-header'>" + selectableHeader + "</div>"
            });
        },
        save: function () {
            var _uId = this._uId;
            
            var _rolForm = $("div[data-id='" + _uId + "']").find("form");
            if (!$(_rolForm).validate().errorList.length > 0) {
                var _name = $("div[data-id='" + _uId + "']").find("div.rol-name input").val();
                var _code = $("div[data-id='" + _uId + "']").find("div.rol-code input").val();
                var _multiProcCapture = $("div[data-id='" + _uId + "']").find("div.process-selection select").val();
                var _processes = [{}];
                if (_multiProcCapture != null) {
                    for (var i = 0 ; i < _multiProcCapture.length ; i++) {
                        _processes[i] = {
                            code: _multiProcCapture[i]
                        }
                    }
                }
                var rol = {
                    code: _code, name: _name, companyId: __currentSession.companyId, processes: _processes
                };
                var model = new RolModel();
                model.Create(rol, function () {
                    require(['controllers/abmManagers/rolManager'], function (Controller) {
                        (new Controller()).show();
                    });
                });
            }
        },
        cancel: function () {
            require(['controllers/abmManagers/rolManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});